import Layout from '@/layout'

const constantRouters = {
  'Layout': Layout,
  'result/success': () => import('@/views/result/success'),
  // 'system/page': () => import('@/views/system/page'),
  // 'system/user': () => import('@/views/system/user'),
  // 'system/menu': () => import('@/views/system/menu'),
  // 'system/role': () => import('@/views/system/role'),
}

/**
 * 动态生成菜单
 *
 * @returns {Promise<Router>}
 */
export const generatorDynamicRouter = (routers) => {
  if(!routers.length) return []
  // 格式化树状
  const currentRouter = listToTree(routers)
  const rootRouter = generator(currentRouter)
    // 404 page must be placed at the end !!!
    rootRouter.push(
      { path: '*', redirect: '/404', hidden: true }
    )
  return rootRouter
}

/**
 * 格式化树形结构数据 生成 vue-router 层级路由表
 *
 * @param routerMap
 * @param parent
 * @returns {*}
 */

function generator(routerMap) {
 return  routerMap.map(item => {
    try {
      (constantRouters[item.component]) || require(`@/views/${item.component}`)
    } catch (error) {
      item.component = '404'
    }

    const currentRouter = {
      path: item.path,
      component:( constantRouters[item.component]) || createComponent(item.component),
      // component: import(`@/views/${item.component}`),
      target: item.target,
      meta: {
        title: item.title,
      }
    }
    if (item.roles && item.roles.length) {
      currentRouter.meta.roles = item.roles

    }
    if (item.icon ) {
      currentRouter.meta.icon = item.icon

    }
    // 激活路径
    if (item.activeMenu) {
      currentRouter.meta.activeMenu = item.activeMenu
    }
    // 重定向
    if (item.redirect) {
      currentRouter.redirect = item.redirect
    }
    // 是否设置了隐藏菜单
    if (item.hidden) {
      currentRouter.hidden = item.hidden
    }
    if (item.children && item.children.length > 0) {
      // Recursion
      currentRouter.children = generator(item.children)
    }
    return currentRouter
  })

}


/**
 *数组转树形结构
 *
 * @param routerMap
 * @param parent
 * @returns {*}
 */

const listToTree = (routerMap, pid = 0) => {
  if (routerMap.length == 1) {
    return routerMap
  }
  let res = JSON.parse(JSON.stringify(routerMap)).filter(val => val.pid == pid)
  res.forEach(val => {
    if (val.pid == pid) {
      let children = listToTree(routerMap, val.id)
      children.length && (val.children = children)
    }
  })
  return res
}

// Generate files that are not placed in the constantrotters map

function createComponent(path){
  return  (resolve) => require([`@/views/${path}`] ,resolve)
}
